package edu.lnu.project.timeeditapp.parser;
/**
 * 
 */

import java.io.File;
import java.util.ArrayList;

/* Added in Referenced Libraries and are need to read the Xls information */
import jxl.Workbook;
import jxl.Sheet;



/**
 * @author Libra
 * 
 * Custom parser for for parsing .xls files dowloaded from https://se.timeedit.net/web/lnu/db1/schema1/
 *
 */
public class XlsParser {

	private final static String WEEKDAY = "Weekday";
	private final static String VECKODAG = "Veckodag";
	
	/**
	 * 
	 * @param sourceFile
	 * @return ArrayList<Event>
	 * @throws Exception
	 */
	public static ArrayList<Event> parseThisFile(File sourceFile) throws Exception{
		
		//ArrayList were we store all event
		ArrayList<Event> events = new ArrayList<Event>();
		
		//Get the workbook instance for the Xls file
		Workbook workbook = Workbook.getWorkbook(sourceFile);
		
		//Get first sheet from the workbook
		Sheet sheet = workbook.getSheet(0);
		
		int numberOfRows = sheet.getRows();
		int startRow = 0;
		//Find row containing weekday/veckodag
		for(int i = startRow; i < numberOfRows; i++){
			int colum = 0, row = i;
			if(sheet.getCell(colum, row).getContents().contains(WEEKDAY) || sheet.getCell(colum, row).getContents().contains(VECKODAG) ){
				startRow = i;
			}
		}
		
		startRow++; //Start making event from row after row containing weekday/veckodag 
		
		//Go through all rows in wookbook and create a event for every row
		for(int row = startRow; row < numberOfRows; row++){
			//Create new event
			Event event = new Event();
			
			//Fill event with information found in the columns of this row
	    	event.setWeekday(sheet.getCell(0, row).getContents());
	    	event.setBeginDate(sheet.getCell(1, row).getContents());
	    	event.setBeginTime(sheet.getCell(2, row).getContents());
	    	event.setEndDate(sheet.getCell(3, row).getContents());
	    	event.setEndTime(sheet.getCell(4, row).getContents());
	    	
	    	event.setCourse(sheet.getCell(5, row).getContents());
	    	event.setProgramme(sheet.getCell(5, row).getContents());
	    	event.setCourseEvt(sheet.getCell(6, row).getContents());
	    	event.setProgrammeEvt(sheet.getCell(6, row).getContents());
	    	
	    	event.setRoom(sheet.getCell(7, row).getContents());
	    	event.setTeacher(sheet.getCell(8, row).getContents());
	    	event.setStudentGroup(sheet.getCell(9, row).getContents());
	    	event.setActivity(sheet.getCell(10, row).getContents());
	    	event.setExamCode(sheet.getCell(11, row).getContents());
	    	event.setComments(sheet.getCell(12, row).getContents());
	    	event.setCity(sheet.getCell(13, row).getContents());	
	    	
	    	// Add the new event to our list of events
		    events.add(event); 
		}

		// Close the workbook when we are done
		workbook.close();
		
		//Return ArrayList<Event>
		return events;
	}
}